package com.company.base.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.company.base.common.WeChatConstant;
import com.company.site.mode.menu.Menu;
import com.company.site.mode.token.AccessToken;
import com.company.site.mode.token.OatuhAccessToken;
import com.company.site.mode.wechatuser.WechatUser;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class WeChatUtil {
	
	private static Logger log = LoggerFactory.getLogger(WeChatUtil.class);
	
	/** 
	 * 获取access_token 
	 *  
	 * @param appid 凭证 
	 * @param appsecret 密钥 
	 * @return 
	 */  
	public static AccessToken getAccessToken(String appid, String appsecret) {  
	    AccessToken accessToken = null;  
	  
	    String requestUrl = WeChatConstant.access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret); 
	    JSONObject jsonObject = httpRequest(requestUrl, "GET", null);  
	    // 如果请求成功  
	    if (null != jsonObject) {  
	        try {  
	            accessToken = new AccessToken();  
	            accessToken.setToken(jsonObject.getString("access_token"));  
	            accessToken.setExpiresIn(jsonObject.getInt("expires_in"));  
	        } catch (JSONException e) {  
	            accessToken = null;  
	            // 获取token失败  
	            log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
	        }  
	    }  
	    return accessToken;  
	}  
	public static OatuhAccessToken getOauthAccessToken(String code) {  
		OatuhAccessToken accessToken = null;  
		String requestUrl = WeChatConstant.oauth_access_token_url.replace("#CODE#", code); 
	    System.out.println(requestUrl);
	    Logger sysLogger = LoggerFactory.getLogger("Exception");
	    sysLogger.info(requestUrl);
	    JSONObject jsonObject = httpRequest(requestUrl, "GET", null);  
//	    String s=sendGet(requestUrl);
//	    System.out.println(s);
//	    JSONArray array = JSONArray.fromObject("["+s+"]") ;
//	   // accessToken = new OatuhAccessToken(); 
//	   // accessToken.setOpenid(s);  
//
//	    JSONObject jsonObject = JSONObject.fromObject(array.get(0));
		// 如果请求成功  
		if (null != jsonObject) {  
			try {  
				accessToken = new OatuhAccessToken();  
				accessToken.setAccess_token(jsonObject.getString("access_token"));  
				accessToken.setExpires_in(jsonObject.getInt("expires_in"));  
				accessToken.setRefresh_token(jsonObject.getString("refresh_token"));  
				accessToken.setOpenid(jsonObject.getString("openid"));  
				accessToken.setScope(jsonObject.getString("scope"));  
			} catch (JSONException e) {  
				System.out.println(e);
				accessToken = null;  
				// 获取token失败  
				log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
			}  
		}  
		return accessToken;  
	}  
	
	/** 
	 * 创建菜单 
	 *  
	 * @param menu 菜单实例 
	 * @param accessToken 有效的access_token 
	 * @return 0表示成功，其他值表示失败 
	 */  
	public static int createMenu(Menu menu, String accessToken) {  
	    int result = 0;  
	  
	    // 拼装创建菜单的url  
	    String url =WeChatConstant.menu_create_url.replace("ACCESS_TOKEN", accessToken);  
	    // 将菜单对象转换成json字符串  
	    String jsonMenu = JSONObject.fromObject(menu).toString(); 
	    System.out.println("jsonMenu="+jsonMenu);
	    // 调用接口创建菜单  
	    JSONObject jsonObject = httpRequest(url, "POST", jsonMenu);  
	  
	    if (null != jsonObject) {  
	        if (0 != jsonObject.getInt("errcode")) {  
	            result = jsonObject.getInt("errcode");  
	            log.error("创建菜单失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
	        }  
	    }  
	  
	    return result;  
	}  
	
	public static int deleteMenu(String accessToken){
		int result = 0;  
		  
	    // 拼装创建菜单的url  
	    String url = WeChatConstant.menu_delete_url.replace("ACCESS_TOKEN", accessToken);  
	    // 调用接口删除菜单  
	    JSONObject jsonObject = httpRequest(url, "GET", null);  
	  
	    if (null != jsonObject) {  
	        if (0 != jsonObject.getInt("errcode")) {  
	            result = jsonObject.getInt("errcode");  
	        }  
	    }  
	  
	    return result;  
	}
	
    /** 
     * 发起https请求并获取结果 
     *  
     * @param requestUrl 请求地址 
     * @param requestMethod 请求方式（GET、POST） 
     * @param outputStr 提交的数据 
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) 
     */  
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {  
        JSONObject jsonObject = null;  
        StringBuffer buffer = new StringBuffer();  
        try {  
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化  
            TrustManager[] tm = { new MyX509TrustManager() };  
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
            sslContext.init(null, tm, new java.security.SecureRandom());  
            // 从上述SSLContext对象中得到SSLSocketFactory对象  
            SSLSocketFactory ssf = sslContext.getSocketFactory();  
  
            URL url = new URL(requestUrl);  
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
            httpUrlConn.setSSLSocketFactory(ssf);  
  
            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            // 设置请求方式（GET/POST）  
            httpUrlConn.setRequestMethod(requestMethod);  
  
            if ("GET".equalsIgnoreCase(requestMethod))  
                httpUrlConn.connect();  
  
            // 当有数据需要提交时  
            if (null != outputStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();  
                // 注意编码格式，防止中文乱码  
                outputStream.write(outputStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  
  
            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  
            jsonObject = JSONObject.fromObject(buffer.toString());  
        } catch (ConnectException ce) {  
            log.error("Weixin server connection timed out.");  
        } catch (Exception e) {  
            log.error("https request error:{}", e);  
        }  
        return jsonObject;  
    }  
	
    public static String sendGet(String urlStr) {
		HttpURLConnection urlConnection = null;
			try {
				URL url = new URL(urlStr);
				urlConnection = (HttpURLConnection) url.openConnection();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		return getContent(urlConnection);
	}

	public static String getContent(HttpURLConnection conn) {
		StringBuilder sb = new StringBuilder();
		InputStream in = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		try {
			in = conn.getInputStream();
			isr = new InputStreamReader(in, "utf-8");
			br = new BufferedReader(isr);

			String line = null;
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (isr != null) {
				try {
					isr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		conn.disconnect();
		return sb.toString();
	}

	public static String sendPost(String urlStr, Map<String, String> param) {
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(urlStr);
		List<NameValuePair> paramList = new ArrayList<NameValuePair>();
		for (Entry<String, String> e : param.entrySet()) {
			paramList.add(new BasicNameValuePair(e.getKey(), e.getValue()));
		}
		try {
			post.setEntity(new UrlEncodedFormEntity(paramList, "utf-8"));
			HttpResponse response = client.execute(post);
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				HttpEntity respEntity = response.getEntity();
				if (respEntity != null) {
					return EntityUtils.toString(respEntity);
				}
			} else {
				System.out.println(urlStr+" response code:"+response.getStatusLine().getStatusCode());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return null;
	}
	
	/**
	 * get WeChat User Information By openid
	 * @param openid
	 * @return User
	 */
	public static WechatUser getUserInfo(String openid){		
		AccessToken at = WeChatUtil.getAccessToken(WeChatConstant.appId, WeChatConstant.appSecret);
		if (null != at) {
			 	String url = WeChatConstant.USER_INFO_URL.replace("ACCESS_TOKEN", at.getToken()).replace("OPENID", openid);  
			    // 
			    JSONObject jsonObject = httpRequest(url, "GET", null);  
			    Object user = JSONObject.toBean(jsonObject, WechatUser.class);  
			    return (WechatUser) user;
		}else{
			return null;
		}
	}
	
	public static String getFansOpenId(){
		AccessToken at = WeChatUtil.getAccessToken(WeChatConstant.appId, WeChatConstant.appSecret);
		if (null != at) {
			 	String url = WeChatConstant.FANS_OPENID_URL.replace("ACCESS_TOKEN", at.getToken());
			    // 
			    JSONObject jsonObject = httpRequest(url, "GET", null);  
			    return jsonObject.toString();
		}else{
			return null;
		}
	}
	
	public long NextInt(final int min, final int max)
	{
		Random rand=new Random();
	    int tmp = Math.abs(rand.nextInt());
	    return tmp % (max - min + 1) + min;
	}
	
	public  long genValidateNum(){
		return NextInt(100000,999999);
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException{
		WechatUser user=getUserInfo("oFzZ7jncI2wQQkwaraxSpW7iEpAc");
		System.out.println(user.getHeadimgurl());
//		AccessToken at = WeChatUtil.getAccessToken(WeChatConstant.appId, WeChatConstant.appSecret);
////		if (null != at) {
//			 	String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN".replace("TOKEN", at.getToken());  
//			     System.out.println(at.getToken());
////			 	url="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=vpnBuxppnlaqo502h0CplArlyVaWn0nr8JevcHqpSISc7PMRP9esbtrckdAgvzEvocNU7jAToBWx0KWOdwPDqa8j933AoNi6WgacdBUP2Qk";
//			 	RequestTicket ticket=new RequestTicket();
//			 	ticket.setExpire_seconds(1800);
//			 	ticket.setAction_name("QR_SCENE");
//			 	Scene scene=new Scene();
//			 	scene.setScene_id(5322);
//			 	ticket.setAction_info(scene);
//			 	String postQrcode=JsonUtil.objectToJson(ticket);
//			 	System.out.println(postQrcode);
//			    JSONObject jsonObject = httpRequest(url, "POST", postQrcode);  
//			    RequestTicket aa = (RequestTicket) JSONObject.toBean(jsonObject, RequestTicket.class);  
//			    System.out.println(jsonObject);
////			    System.out.println(aa.getUrl());
//			    
////			    JSONObject get = httpRequest("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET".replace("TICKET", aa.getTicket()), "GET", null);   
////			    System.out.println(get);
//			   
////		}else{
////			
////		}
	}
	
	
}
